﻿using ICSharpCode.AvalonEdit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using PDFDesign.Command;
using MahApps.Metro.Controls.Dialogs;
using Newtonsoft.Json;
using PDFDesign.Model;

namespace PDFDesign.ViewModel
{
    public class SaveDataViewModel : BaseViewModel
    {
        private TextEditor textEditor;

        public SaveDataViewModel(TextEditor textEditor)
        {
            this.textEditor = textEditor;
        }

        private string name;
        public string Name
        {
            get => name;
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }

        public ICommand AddCommand
        {
            get => new AnotherCommand(_ =>
            {
                if (string.IsNullOrWhiteSpace(Name))
                {
                    ShowMessage("请输入数据名称");
                    return;
                }
                object obj = null;
                try
                {
                    obj = JsonConvert.DeserializeObject(textEditor.Text);
                    if (obj == null)
                    {
                        ShowMessage("数据格式错误");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage($"数据格式错误：{ex.Message}");
                    return;
                }
                SaveData = new SaveData
                {
                    Name = name,
                    Data = textEditor.Text
                };
                DialogResult = true;
            });
        }

        private bool? dialogResult;
        public bool? DialogResult
        {
            get => dialogResult;
            set
            {
                dialogResult = value;
                OnPropertyChanged("DialogResult");
            }
        }

        public SaveData SaveData { get; set; }

        /// <summary>
        /// 提示消息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMessage(string message) => DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", message, MessageDialogStyle.Affirmative);
    }
}
